package com.zsk.shop.service;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsk.shop.common.base.BaseResponse;
import com.zsk.shop.common.base.BizException;
import com.zsk.shop.common.base.NoMsgException;
import com.zsk.shop.common.base.page.BasePageFactory;
import com.zsk.shop.common.base.page.BasePageParams;
import com.zsk.shop.common.utils.EntityConvertUtils;
import com.zsk.shop.common.utils.RedisUtil;
import com.zsk.shop.common.utils.ToolUtil;
import com.zsk.shop.entity.ShopGoods;
import com.zsk.shop.entity.ShopGoodsLabel;
import com.zsk.shop.enums.ServiceKeyTypeEnum;
import com.zsk.shop.mapper.ShopGoodsLabelMapper;
import com.zsk.shop.model.params.HomeGoodsByLabelParams;
import com.zsk.shop.model.params.ShopGoodsLabelAddParams;
import com.zsk.shop.model.params.ShopGoodsLabelEditParams;
import com.zsk.shop.model.results.HomeGoodsLabelList;
import com.zsk.shop.model.results.HomeGoodsResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author ljh
 * @create 2021/11/17 16:12
 */
@Service
@DS("miniShop")
public class ShopGoodsLabelService extends ServiceImpl<ShopGoodsLabelMapper, ShopGoodsLabel> {

    private static final Logger logger = LoggerFactory.getLogger(ShopGoodsLabelService.class);

    @Resource
    private ShopGoodsService shopGoodsService;

    public BaseResponse<List<HomeGoodsLabelList>> goodsLabelList() {
        List<HomeGoodsLabelList> result = new ArrayList<>();
        LambdaQueryWrapper<ShopGoodsLabel> queryWrapper = new
                LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(ShopGoodsLabel::getSort);
        queryWrapper.eq(ShopGoodsLabel::getIsDeleted, false);
        queryWrapper.eq(ShopGoodsLabel::getIsShow, true);
        List<ShopGoodsLabel> list = list(queryWrapper);
        HomeGoodsByLabelParams params = HomeGoodsByLabelParams.builder().build();
        params.setLimit("4");
        params.setPage("1");
        params.setAccordingLabelShow(true);
        for (ShopGoodsLabel shopGoodsLabel : list) {
            params.setLabelNo(shopGoodsLabel.getLabelNo());
            List<HomeGoodsResult> labelResultList = shopGoodsService.goodsByLabelList(params).getData();
            HomeGoodsLabelList homeGoodsLabelList = new HomeGoodsLabelList();
            homeGoodsLabelList.setLabelNo(shopGoodsLabel.getLabelNo());
            homeGoodsLabelList.setLabelName(shopGoodsLabel.getLabelName());
            homeGoodsLabelList.setGoodsList(labelResultList);
            result.add(homeGoodsLabelList);
        }
        return BaseResponse.success(result);
    }

    public BaseResponse addGoodsLabel(ShopGoodsLabelAddParams params) {
        ShopGoodsLabel shopGoodsLabel = EntityConvertUtils.convertAToB(params, ShopGoodsLabel.class);
        shopGoodsLabel.setLabelNo(RedisUtil.getServiceKeyHaveDateByType(ServiceKeyTypeEnum.GOODS_LABEL.getValue()));
        shopGoodsLabel.setSort(ToolUtil.isNotEmpty(params.getSort()) ? params.getSort() : 0);
        shopGoodsLabel.setIsShow(true);
        shopGoodsLabel.setIsDeleted(false);
        Date time = new Date();
        shopGoodsLabel.setCreateTime(time);
        saveOrUpdate(shopGoodsLabel);
        return BaseResponse.success("成功");
    }

    public ShopGoodsLabel queryByLabelNo(String labelNo) {
        if (ToolUtil.isEmpty(labelNo)) {
            return null;
        }
        LambdaQueryWrapper<ShopGoodsLabel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopGoodsLabel::getLabelNo, labelNo);
        return getOne(queryWrapper);
    }

    public BaseResponse editGoodsLabel(ShopGoodsLabelEditParams params) {
        LambdaUpdateWrapper<ShopGoodsLabel> updateWrapper = new LambdaUpdateWrapper<>();
        if (ToolUtil.isNotEmpty(params.getSort())) {
            updateWrapper.set(ShopGoodsLabel::getSort, params.getSort());
        }
        if (ToolUtil.isNotEmpty(params.getLabelName())) {
            updateWrapper.set(ShopGoodsLabel::getLabelName, params.getLabelName());
        }
        updateWrapper.set(ShopGoodsLabel::getUpdateTime, new Date());
        updateWrapper.eq(ShopGoodsLabel::getId, params.getId());
        this.update(updateWrapper);
        return BaseResponse.success("修改成功");
    }

    @Transactional(rollbackFor = {Exception.class, BizException.class, NoMsgException.class})
    public BaseResponse reviewGoodsLabel(Long id, Boolean letDisable) {
        ShopGoodsLabel shopGoodsLabel = getById(id);
        String labelNo = shopGoodsLabel.getLabelNo();
        //禁用（查询是否有挂靠商品）
        if (letDisable) {
            List<ShopGoods> shopGoodsList = shopGoodsService.queryByLabelNo(labelNo);
            if (ToolUtil.isNotEmpty(shopGoodsList)) {
                ShopGoods shopGoods = shopGoodsList.get(0);
                throw new NoMsgException("当前标签下,至少还存在商品【" + shopGoods.getGoodsName() + "】挂靠在该标签下");
            }
            shopGoodsLabel.setIsShow(false);
        } else {
            shopGoodsLabel.setIsShow(true);
        }
        this.saveOrUpdate(shopGoodsLabel);
        return BaseResponse.success("禁启用商品标签成功");
    }

    @Transactional(rollbackFor = {Exception.class, BizException.class, NoMsgException.class})
    public BaseResponse deleteGoodsLabel(Long id) {
        ShopGoodsLabel shopGoodsLabel = getById(id);
        String labelNo = shopGoodsLabel.getLabelNo();
        //（查询是否有挂靠商品）
        List<ShopGoods> shopGoodsList = shopGoodsService.queryByLabelNo(labelNo);
        if (ToolUtil.isNotEmpty(shopGoodsList)) {
            ShopGoods shopGoods = shopGoodsList.get(0);
            throw new NoMsgException("当前标签下,至少还存在商品【" + shopGoods.getGoodsName() + "】没有删除");
        }
        shopGoodsLabel.setUpdateTime(new Date());
        shopGoodsLabel.setIsDeleted(true);
        this.saveOrUpdate(shopGoodsLabel);
        return BaseResponse.success("删除商品标签成功");
    }

    public BaseResponse<List<ShopGoodsLabel>> gopGoodsLabelList(@RequestBody BasePageParams params) {
        Page pageContext = BasePageFactory.defaultPage(params.getPage(), params.getLimit());
        LambdaQueryWrapper<ShopGoodsLabel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopGoodsLabel::getIsDeleted, false);
        queryWrapper.orderByAsc(ShopGoodsLabel::getSort, ShopGoodsLabel::getUpdateTime);
        IPage page = this.page(pageContext, queryWrapper);
        List<ShopGoodsLabel> shopGoodsLabelList = page.getRecords();
        List<ShopGoodsLabel> result = EntityConvertUtils.convertAListToBList(shopGoodsLabelList, ShopGoodsLabel.class);
        //所有商品SKU集合
        for (ShopGoodsLabel s : result) {

        }
        page.setRecords(result);
        return BasePageFactory.createPageInfo(page);
    }

    public List<ShopGoodsLabel> labelList() {
        LambdaQueryWrapper<ShopGoodsLabel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopGoodsLabel::getIsDeleted, false);
        return list(queryWrapper);
    }
}
